var api = require('./utils/request');
var util = require('./utils/util');
var siteInfo = require('config.js');
App({
  /**
   * 全局变量
   */
  globalData: {
    loginuser:{},
    ucode:'',
    isAndroid: false,
  },

  /**
   * 生命周期函数--监听小程序初始化
   */
  onLaunch: function (options) {
    this.apiroot = siteInfo.siteroot; //设置api地址
    this.appname = siteInfo.name; //设置应用名称
    this.getParam(options);
    this.updateMiniapp();  //小程序更新
    this.isAndroid();      //判断操作系统是Android/iOS
    this.config();          //获取配置

  },
  //应用配置
  config: function () {
    //登录用户信息
    if (!util.isNull(wx.getStorageSync('loginuser'))) {
      this.globalData.loginuser = wx.getStorageSync('loginuser');
    }
  },
  //用全局变量保存邀请码
  getParam: function (options,callback) {
    let that = this;
    if (options.scene) {
      var options = util.strToArray(decodeURIComponent(options.scene));
      if (!util.isNull(options.ucode)) {
        that.globalData.ucode = options.ucode;
      }
    } else {
      if (!util.isNull(options.ucode)) {
        that.globalData.ucode = options.ucode;
      }
    }
    typeof callback == "function" && callback(options)
  },
  //登录状态
  loginState:function (callback) {
    var session_id = wx.getStorageSync('session_id'),
        token      = wx.getStorageSync('token'),
        loginuser  = wx.getStorageSync('loginuser');
    if(util.isNull(session_id) || util.isNull(token) || util.isNull(loginuser)){
      typeof callback == "function" && callback(false)
    }else{
      typeof callback == "function" && callback(true)
    }
  },
  /**
   * 微信小程序登录
   */
  doLogin: function (options,callback) {
    let that = this;
    wx.login({
      success: function (res) {
        api.Post('openapi/v1/weapp/login', {
          code: res.code,
          iv:options.detail.iv,
          invitecode: app.globalData.ucode,
          encryptedData:options.detail.encryptedData
        }, function (result) {
          wx.setStorageSync('token', result.data.token);
          wx.setStorageSync('session_id', result.data.session_id);
          wx.setStorageSync('loginuser', result.data);
          that.globalData.loginuser = result.data;
          callback && callback(true);
        })
      },
      fail: function () {
        callback && callback(false);
      }
    });
  },
  /**
  * 调用微信支付
  */
 doPay: function (data, successCallback, failCallback) {
    var dataMap = {
      timeStamp: data.timestamp,
      nonceStr: data.nonceStr,
      package: data.package,
      signType: data.signType,
      paySign: data.paySign,
      success: successCallback,
      fail: failCallback
    }
    wx.requestPayment(dataMap);
  },
  /**
   * 更新小程序
   */
  updateMiniapp: function () {
    if (wx.canIUse('getUpdateManager')) {
      const updateManager = wx.getUpdateManager()
      //判断是否有新的小程序
      updateManager.onCheckForUpdate(function (res) {
        if (res.hasUpdate) {
          updateManager.onUpdateReady(function () {
            wx.clearStorage()   //清理缓存
            wx.showModal({
              showCancel: false,
              title: '更新提示',
              content: '新版本已经升级完成，请重启应用!',
              success: function (res) {
                updateManager.applyUpdate()
              }
            })
          })
          //新的版本下载失败
          updateManager.onUpdateFailed(function () {
            wx.showModal({
              showCancel: false,
              title: '已经有新版本了哟~',
              content: '新版本自动升级失败了~请您删除当前小程序，重新搜索打开哟~',
              success: function (res) {
                updateManager.applyUpdate()
              }
            })
          })
        }
      })
    } else {
      wx.showModal({
        title: '提示',
        content: '当前微信版本过低，无法使用该功能，请升级到最新微信版本后重试。'
      })
    }
  },
  /**
   * 判断操作系统是Android/iOS
   */
  isAndroid: function () {
    let that = this;
    wx.getSystemInfo({
      success: function (res) {
        that.globalData.isAndroid = res.platform == "ios" ? false : true
      }
    })
  },
  /**
  * 确认窗口并返回
  */
  wxLayer: function (message, callback) {
    wx.showModal({
      content: message,
      success:(rel)=>{
        if (rel.confirm) {
          typeof callback == "function" && callback()
        }
      }
    })
  },
  /**
   * 弹窗提示
   */
  wxAlert: function (message,callback) {
    wx.showModal({
      content: message,showCancel: false,
      success: (rel) => {
        if (rel.confirm) {
          typeof callback == "function" && callback()
        }
      }
    })
  },
  /**
   * 调用API
   */
  api:function(){
    return api;
  },
  util: function () {
    return util;
  }
});